﻿using System;
using System.Diagnostics;
using MsSqlCeTest.Core.Domain;
using NHibernate;
using NHibernate.Cfg;

namespace MsSqlCeTest
{
	class Program
	{
		#region Constants

		private const int ITEMS_COUNT = 1000;

		#endregion Constants

		#region Fields

		private static ISessionFactory sessionFactory;

		#endregion Fields

		#region Properties

		private static ISessionFactory SessionFactory
		{
			get
			{
				if (sessionFactory == null)
				{
					var configuration = new Configuration();
					configuration.Configure();

					sessionFactory = configuration.BuildSessionFactory();
				}

				return sessionFactory;
			}
		}

		#endregion Properties

		#region Main

		static void Main()
		{
			try
			{
				LoadItems();
				CreateItems();
				LoadItems();
			}
			catch (Exception e)
			{
				Console.WriteLine(e);
			}
			finally
			{
				Console.ReadKey();
			}
		}

		#endregion Main

		#region Helpers

		private static void CreateItems()
		{
			Console.WriteLine("Creating items");

			var stopWatch = new Stopwatch();
			stopWatch.Start();

			using (var session = SessionFactory.OpenSession())
			{
				using (var transaction = session.BeginTransaction())
				{
					for (int i = 0; i < ITEMS_COUNT; i++)
					{
						var item = new Item {Description = string.Format("Item #{0}", i)};
						session.Save(item);
					}

					transaction.Commit();
				}
			}

			Console.WriteLine(string.Format("Time elapsed: {0}\n", stopWatch.Elapsed));
		}

		private static void LoadItems()
		{
			Console.WriteLine("Loading items");

			var stopWatch = new Stopwatch();
			stopWatch.Start();

			using (var session = SessionFactory.OpenSession())
			{
				var criteria = session.CreateCriteria(typeof(Item));
				var items = criteria.List<Item>();
				Console.WriteLine("Got {0} items", items.Count);
			}

			Console.WriteLine(string.Format("Time elapsed: {0}\n", stopWatch.Elapsed));
		}

		#endregion Helpers
	}
}
